package com.google.code.etrclient;

import com.google.code.etrclient.helper.IETRClientConstants;
import com.google.code.etrclient.helper.ServiceCalls;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ETRMainActivity extends Activity implements IETRClientConstants {
  private Handler handler;
  private TextView tvMain;
  private ProgressBar pbarHeaderProgress;
  private ImageButton btnHeaderRefresh;
  private String uiText = "";
  private String username;
  private String password;
  private String language;
  
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    handler = new Handler();
    
    setContentView(R.layout.main);
    tvMain = (TextView)findViewById(R.id.tvMain);
    pbarHeaderProgress = (ProgressBar)findViewById(R.id.pbarHeaderProgress);
    btnHeaderRefresh = (ImageButton)findViewById(R.id.btnHeaderRefresh);
    btnHeaderRefresh.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        refresh();
      }
    });
    
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    username = sharedPreferences.getString("username", "");
    password = sharedPreferences.getString("password", "");
    language = sharedPreferences.getString("language", "");
        
    refresh();
  }
  
  @Override
  public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
  }
  
  private void refresh() {
    pbarHeaderProgress.setVisibility(View.VISIBLE);
    new Thread(new Runnable() {
      @Override
      public void run() {
        uiText = ServiceCalls.loginAndGetFirstPage(username, password, language);
        handler.post(updateUI);
      }
    }).start();
  }
  
  private Runnable updateUI = new Runnable() {
    @Override
    public void run() {
      tvMain.setText(uiText);
      pbarHeaderProgress.setVisibility(View.GONE);
    }
  };
    
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.mi_prefs:
        startActivity(new Intent(this, ETRPreferencesActivity.class));
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
}